import 'package:dk_flutter_base/dk_ui.dart';
import 'package:dk_flutter_base/dk_core.dart';
import 'package:dk_flutter_module_sale/common/config/page_base_common.dart';
import 'package:dk_flutter_module_sale/common/user_track/user_track.dart';
import 'package:dk_flutter_module_sale/config/route/common_widget_route.dart';
import 'package:dk_flutter_module_sale/phoenix/api/revision_main_api.dart';
import 'package:dk_flutter_module_sale/phoenix/common/widget/dk_underline_tabindicator.dart';
import 'package:dk_flutter_module_sale/phoenix/tools/bean/bean_tools_item.dart';
import 'package:dk_flutter_module_sale/phoenix/tools/bean/bean_tools_module.dart';
import 'package:dk_flutter_module_sale/phoenix/tools/bean/event_bus_select_tool_category.dart';
import 'package:dk_flutter_module_sale/phoenix/tools/widget/widget_tools_editItem.dart';
import 'package:dk_flutter_module_sale/phoenix/tools/widget/widget_tools_modules.dart';

@ARoute(url: CommonWidgetRoute.EDIT_TOOLS)
class EditToolsPage extends CommonPage {
  final WidgetOption option;
  EditToolsPage(this.option) : super();

  @override
  void onInitState(CommonPageBloc pageBloc) {
    pageBloc.pageHttpGet(
        // path: "http://72.18.130.18:8190/wutongshu/tools/editTools",
        path: RevisionMainApi.editToolsList,
        widgetBuilderByData: (dynamic data) {
          BeanToolsModule module = BeanToolsModule.fromJson(data);
          return EditToolsWidget(pageBloc, module);
        });
  }
}

class _EditStatusBloc extends EventBloc<bool> {
  @override
  bool get initialState => false; //false标识普通状态，ture标识页面处于编辑状态
}

class _EditItemBloc extends EventBloc<ToolsEditResultEvent> {
  @override
  ToolsEditResultEvent get initialState =>
      ToolsEditResultEvent(editStatusType.editStatusTypeNone, null);
}

class EditToolsWidget extends StatefulWidget {
  final BeanToolsModule beanModule;
  final CommonPageBloc pageBloc;
  EditToolsWidget(this.pageBloc, this.beanModule, {Key key}) : super(key: key);

  _EditToolsWidgetState createState() => _EditToolsWidgetState();
}

class _EditToolsWidgetState extends State<EditToolsWidget>
    with SingleTickerProviderStateMixin {
  TabController controller;
  bool widgetEditStatus = false; //编辑状态
  int selectedIndex = 0;
  _EditStatusBloc editStatusBloc; //编辑状态bloc
  _EditItemBloc editItemBloc; //编辑结果bloc
  List<ToolsItem> commonToolsOriginList; //常用工具网络请求回来的数据源
  List<ToolsItem> commonToolsList; //常用可操作数据源
  List<CategoryListBean> categoryOriginBeanList; //更多工具内容列表
  List<CategoryListBean> categoryBeanList; //更多工具可操作数据源

  @override
  void initState() {
    super.initState();
    UserTrack.trackViewScreen("公共工具编辑", null);
    editStatusBloc = _EditStatusBloc();
    editItemBloc = _EditItemBloc();

    // categoryOriginBeanList = widget.beanModule?.moreToolsModlue?.list;
    categoryOriginBeanList = _getNewCategoryBeanList();
    categoryBeanList = _getCloneCategoryBeanList();
    controller = TabController(
        length: categoryBeanList.length, vsync: this, initialIndex: 0)
      ..addListener(() {
        setState(() {
          selectedIndex = controller.index;
        });
      });
    commonToolsOriginList = widget.beanModule?.commonToolsModule?.tools;
    commonToolsList = _getCloneCommonToolsList();

    //监听编辑状态的更改
    widget.pageBloc.eventBus
        .on<ToolsEditStatusEvent>()
        .listen((ToolsEditStatusEvent event) {
      editStatusBloc?.dispatch(event.status);
    });

    //监听编辑增加或删减事件
    widget.pageBloc.eventBus
        .on<ToolsEditResultEvent>()
        .listen((ToolsEditResultEvent event) {
      editItemBloc?.dispatch(event);
    });
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder(
      bloc: editStatusBloc,
      builder: (BuildContext context, bool editStatus) {
        widgetEditStatus = editStatus;
        String rightTitle = (editStatus == true) ? "完成" : "编辑";
        return BlocBuilder(
          bloc: editItemBloc,
          builder: (BuildContext context, ToolsEditResultEvent event) {
            editEvent(event);
            return Scaffold(
              appBar: PreferredSize(
                child: SafeArea(
                  child: Container(
                    width: 375,
                    child: Row(
                      children: <Widget>[
                        _getBarLeftItem(),
                        Expanded(
                          child: Text(
                            '更多',
                            style: TextStyle(
                                color: Color(0xff333333),
                                fontSize: 17,
                                fontWeight: FontWeight.bold),
                            textAlign: TextAlign.center,
                          ),
                        ),
                        _getBarItem(rightTitle),
                      ],
                    ),
                  ),
                ),
                preferredSize: Size.fromHeight(44),
              ),
              body: _buidBody(context),
            );
          },
        );
      },
    );
  }

  Widget _getBarLeftItem() {
    if (widgetEditStatus) {
      return _getBarItem('取消');
    }
    return InkWell(
      onTap: () async => RouteUtil.pop(context, result: {'needRefresh': false}),
      child: Container(
          width: 70,
          padding: EdgeInsets.only(left: 5),
          alignment: Alignment.centerLeft,
          child: Image.asset(
              Env?.value?.dkAppBarGlobalParams?.backArrowPath ?? "")),
    );
  }

  Widget _getBarItem(String title) {
    return Container(
      alignment: Alignment.center,
      width: 70,
      padding: EdgeInsets.symmetric(horizontal: 14),
      child: GestureDetector(
        onTap: () {
          setState(() {
            if (title == '取消') {
              editStatusBloc.dispatch(!widgetEditStatus);
              //点击取消，恢复排序之前的数据源
              commonToolsList = _getCloneCommonToolsList();
              categoryBeanList = _getCloneCategoryBeanList();
            } else if (title == '完成') {
              //点击完成，请求保存接口，并且通知上级页面刷新数据源

              String toolStr = "";
              for (var i = 0; i < commonToolsList.length; i++) {
                if (stringNotEmpty(commonToolsList[i].bizCode)) {
                  toolStr += (commonToolsList[i].bizCode);
                }
                if (commonToolsList.length > 1 &&
                    i != commonToolsList.length - 1) {
                  toolStr += ';';
                }
              }
              var map = {
                'myToolsList': toolStr,
              };
              widget.pageBloc.dataHttpPost(
                data: map,
                path: RevisionMainApi.editToolsSort,
                handleResult: (dynamic data) {
                  RouteUtil.pop(context, result: {'needRefresh': true});
                },
                handleErrorCode: (responseData) {
                  showCenterToast(responseData?.msg ?? "保存失败，请稍后再试！",duration: Duration(milliseconds: 3000));
                },
                showFailMsg: true,
                showLoading: true,
              );
            } else if (title == '编辑') {
              editStatusBloc.dispatch(!widgetEditStatus);
            }
          });
        },
        child: Text(title,
            style: TextStyle(fontSize: 15, color: Color(0xff3274F9))),
      ),
    );
  }

  Widget _buidBody(BuildContext context) {
    return Container(
        width: 375,
        height: double.infinity,
        child: Material(
          color: Colors.white,
          child: (commonToolsOriginList.length == 0 &&
                  categoryOriginBeanList.length == 0)
              ? LogicPage.emptyPage(emptyParam: SaleConfig.emptyPageParam)
              : ListView.builder(
                  shrinkWrap: true,
                  scrollDirection: Axis.vertical,
                  itemCount: 2,
                  itemBuilder: (BuildContext context, int index) {
                    if (index == 0) {
                      return Column(
                        children: <Widget>[
                          Container(
                            height: 10,
                            color: Color(0xfff5f5f5),
                          ),
                          ToolsModuleTitle(
                              widget.beanModule?.commonToolsModule
                                      ?.moduleName ??
                                  "我的常用工具",
                              rightNum: "${commonToolsList.length}"),
                          commonToolsList.length > 0
                              ? ToolsDragSortWidget(
                                  commonToolsList,
                                  widget.pageBloc.eventBus,
                                  status: widgetEditStatus,
                                  onTap: (item) {
                                    itemOnTap(item);
                                  },
                                )
                              : Container(
                                  width: 375,
                                  height: 106,
                                  child: Center(
                                    child: DkText.simple(
                                      widgetEditStatus
                                          ? '点击下方加号图标添加'
                                          : '点击编辑进行添加',
                                      13,
                                      Color(0xff999999),
                                      fontWeight: FontWeight.normal,
                                    ),
                                  ),
                                ),
                          Container(
                            height: 10,
                            color: Color(0xfff5f5f5),
                          ),
                        ],
                      );
                    } else if (index == 1) {
                      return Column(
                        mainAxisSize: MainAxisSize.min,
                        children: <Widget>[
                          ToolsModuleTitle(
                              widget.beanModule?.moreToolsModlue?.moduleName ??
                                  "更多工具"),
                          Container(
                            alignment: Alignment.centerLeft,
                            padding: EdgeInsets.only(left: 16),
                            child: TabBar(
                              isScrollable: true,
                              controller: controller,
                              unselectedLabelColor: Color(0xff999999),
                              labelColor: Color(0xff3274F9),
                              labelStyle: TextStyle(
                                  fontSize: 16, fontWeight: FontWeight.w500),
                              unselectedLabelStyle: TextStyle(fontSize: 16),
                              indicatorColor: Color(0xff3274F9),
                              indicator: DKUnderlineTabIndicator(
                                wantWidth: 20,
                                borderSide: BorderSide(
                                  width: 2,
                                  color: Color(0xff3274F9),
                                ),
                              ),
                              indicatorSize: TabBarIndicatorSize.label,
                              tabs: categoryBeanList
                                  ?.map((CategoryListBean bean) {
                                return new Tab(text: bean?.categoryName ?? "");
                              })?.toList(),
                            ),
                          ),
                          DkDivider(DividerOption.horizontal(height: 0.5)),
                          categoryOriginBeanList.length > 0
                              ? Flexible(
                                  child: IndexedStack(
                                    index: selectedIndex,
                                    children: categoryBeanList
                                        ?.map((CategoryListBean bean) {
                                      return ToolsCategoryContentWidget(
                                        bean.tools,
                                        widget.pageBloc.eventBus,
                                        status: widgetEditStatus,
                                        commonToolsCount:
                                            commonToolsList?.length,
                                        onTap: (item) {
                                          itemOnTap(item);
                                        },
                                      );
                                    })?.toList(),
                                  ),
                                )
                              : SizedBox(),
                        ],
                      );
                    }

                    return SizedBox();
                  }),
        ));
  }

  void itemOnTap(ToolsItem item) {
    RouteUtil.goPage(item.appRouteUrl, widgetContext: context);
     Map<String,dynamic> map = Map<String,dynamic>();
     map["name"] = item.title;
     UserTrack.track("click_edit_tools_item", map);
  }

  //---------------处理数据相关逻辑-----------------------------
  List<CategoryListBean> _getNewCategoryBeanList() {
    //首次请求回来的更多里面排重常用数据
    //首次排重的更多工具数据
    List<CategoryListBean> categoryList =
        widget.beanModule?.moreToolsModlue?.list;
    List<ToolsItem> commonTools = widget.beanModule?.commonToolsModule?.tools;
    if (commonTools.length == 0) {
      return categoryList;
    } else {
      for (var i = 0; i < commonTools.length; i++) {
        ToolsItem item = commonTools[i];
        for (var i = 0; i < categoryList.length; i++) {
          CategoryListBean bean = categoryList[i];
          if (bean.categoryId == item.categoryId) {
            for (var i = 0; i < bean.tools.length; i++) {
              if (bean.tools[i].bizCode == item.bizCode) {
                bean.tools.removeAt(i);
                break;
              }
            }
            break;
          }
        }
      }
      return categoryList;
    }
  }

  List<ToolsItem> _getCloneCommonToolsList() {
    //常用工具列表数据副本
    commonToolsList?.removeRange(0, commonToolsList.length);
    List<ToolsItem> items = new List();
    for (var i = 0; i < commonToolsOriginList.length; i++) {
      Map json = commonToolsOriginList[i].toJson();
      ToolsItem item = ToolsItem.fromJson(json);
      items.add(item);
    }
    return items;
  }

  List<CategoryListBean> _getCloneCategoryBeanList() {
    //更多工具数据副本
    categoryBeanList?.removeRange(0, categoryBeanList.length);
    List<CategoryListBean> items = new List();
    for (var i = 0; i < categoryOriginBeanList.length; i++) {
      Map json = categoryOriginBeanList[i].toJson();
      CategoryListBean item = CategoryListBean.fromJson(json);
      items.add(item);
    }

    List<ToolsItem> allTools = new List();
    for (var i = 0; i < items.length; i++) {
      CategoryListBean item = items[i];
      List<ToolsItem> tools = item.tools ?? List();
      for (var i = 0; i < tools.length; i++) {
        //添加业务线标识
        tools[i].categoryId = item.categoryId;
      }
      allTools.addAll(tools);
    }
    //添加全部
    if (items.length > 0) {
      CategoryListBean bean = CategoryListBean(
          categoryName: '全部', categoryId: '9999', tools: allTools);
      items.insert(0, bean);
    }

    return items;
  }

  void editEvent(ToolsEditResultEvent event) {
    //点击新增或删除后的数据源排重��改
    if (event?.type == editStatusType.editStatusTypeAdd) {
      //添加事件
      //常用工具新增
      commonToolsList?.add(event.item);

      for (var i = 0; i < categoryBeanList[0].tools.length; i++) {
        //全部下面找到相关item
        if (categoryBeanList[0].tools[i].bizCode == event.item.bizCode) {
          categoryBeanList[0].tools.remove(categoryBeanList[0].tools[i]);
          break;
        }
      }

      for (var i = 1; i < categoryBeanList.length; i++) {
        CategoryListBean bean = categoryBeanList[i];
        if (bean.categoryId == event.item.categoryId) {
          //找到除全部的所属分类
          for (var i = 0; i < bean.tools.length; i++) {
            if (bean.tools[i].bizCode == event.item.bizCode) {
              bean?.tools?.remove(bean.tools[i]);
              break;
            }
          }
          break;
        }
      }
    } else if (event?.type == editStatusType.editStatusTypeSub) {
      //常用工具点击减去事件
      categoryBeanList[0]?.tools?.insert(0, event.item); //全部
      for (var i = 1; i < categoryBeanList.length; i++) {
        CategoryListBean bean = categoryBeanList[i];
        if (bean.categoryId == event.item.categoryId) {
          bean?.tools?.insert(0, event.item);
          break;
        }
      }
    }
    event.type = editStatusType.editStatusTypeNone;
  }
}
